<template>
	<a-drawer v-bind="options">
		<a-tabs v-model:activeKey="activeKey" type="card" class="dialog-card-container">
			<template #rightExtra>
				<close-outlined class="cursor-pointer" @click="options.onClose()" />
			</template>
			<a-tab-pane key="info" tab="基本信息">
				<a-skeleton :loading="loadings.detail" active :paragraph="{rows: 15}">
					<a-descriptions class="ant-descriptions-blockquote" title="账单信息" :column="2">
						<a-descriptions-item label="房源地址" :span="2">
							<a-tag v-if="detail.houseAlias" color="processing">{{ detail.houseAlias }}</a-tag>
							{{ detail.houseAddress }}
						</a-descriptions-item>
						<a-descriptions-item label="账单类型">{{ detail.billTypeName }}</a-descriptions-item>
						<a-descriptions-item label="账单来源">{{ detail.bizTypeName }}</a-descriptions-item>
						<a-descriptions-item label="账单周期" :span="2">
							{{ formatDate(detail.bizStartTime) }}
							至
							{{ formatDate(detail.bizEndTime) }}
						</a-descriptions-item>
						<a-descriptions-item label="账单备注" :span="2">{{ detail.billComment }}</a-descriptions-item>
						<a-descriptions-item label="账单凭证" :span="2">
							<file-upload :files="detail.billAttachment" only-show-preview />
						</a-descriptions-item>
					</a-descriptions>
					<a-descriptions class="ant-descriptions-blockquote" title="银行流水信息" :column="2">
						<a-descriptions-item label="客户信息" :span="2">{{ detail.bankFlowInfoDTO?.payInfo }}</a-descriptions-item>
						<a-descriptions-item label="支付方式">{{ detail.bankFlowInfoDTO?.paymentAccountType }}</a-descriptions-item>
						<a-descriptions-item label="支付类型">
							{{ detail.bankFlowInfoDTO?.bankFlowType ? mapBankFlowType[detail.bankFlowInfoDTO?.bankFlowType] : '' }}
						</a-descriptions-item>
						<a-descriptions-item label="客户账号" :span="2">{{ detail.bankFlowInfoDTO?.payAccount }}</a-descriptions-item>
						<a-descriptions-item label="支付金额">{{ detail.bankFlowInfoDTO?.price }}</a-descriptions-item>
						<a-descriptions-item label="支付手续费">{{ detail.bankFlowInfoDTO?.handlingFee }}</a-descriptions-item>
						<a-descriptions-item label="实际支付金额" :span="2">{{ detail.bankFlowInfoDTO?.actualPrice }}</a-descriptions-item>
						<a-descriptions-item label="支付流水号" :span="2">{{ detail.bankFlowInfoDTO?.orderNo }}</a-descriptions-item>
						<a-descriptions-item label="渠道订单号">{{ detail.bankFlowInfoDTO?.outTradeNo }}</a-descriptions-item>
						<a-descriptions-item label="提交时间">{{ detail.createTime }}</a-descriptions-item>
						<a-descriptions-item label="支付发起时间">{{ detail.bankFlowInfoDTO?.orderBeginTime }}</a-descriptions-item>
						<a-descriptions-item label="支付完成时间">{{ detail.bankFlowInfoDTO?.payDateTime }}</a-descriptions-item>
						<a-descriptions-item label="经办人" :span="2">
							{{ detail.affirmEmpName }}
						</a-descriptions-item>
						<a-descriptions-item label="支付备注" :span="2">{{ detail.comment }}</a-descriptions-item>
						<a-descriptions-item label="支付凭证" :span="2">
							<file-upload :files="detail.flowAttachment as []" only-show-preview />
						</a-descriptions-item>
					</a-descriptions>
					<template v-if="detail.billDetailInfoList && detail.billDetailInfoList.length">
						<a-typography-text strong>
							<blockquote :style="{'margin-top': 0, display: 'inline-block'}">流水明细</blockquote>
							<a-button
								:disabled="!detail.bankFlowInfoDTO || 1 !== detail.bankFlowInfoDTO.bankFlowType"
								style="margin-left: 10px"
								size="small"
								type="primary"
								@click="openBillRecordDialog">
								关联核销记录
							</a-button>
						</a-typography-text>
						<vxe-table
							show-footer
							show-overflow
							ref="xTable"
							:footer-method="footerMethod"
							:data="detail.billDetailInfoList"
							size="small"
							highlight-hover-row>
							<vxe-column title="费用科目" field="feeSubjectName" min-width="200">
								<template #default="{row}">
									{{ row.feeSubjectName }}：{{ row.attributionType === 1 ? '企业承担' : '个人承担' }}
								</template>
							</vxe-column>
							<vxe-column title="金额" field="money" min-width="100">
								<template #default="{row}">
									{{ row.feeDirection === 1 ? '+' : '-' }}
									{{ row.money.toLocaleString() }}
								</template>
							</vxe-column>
							<!-- <vxe-column title="优惠券" width="150">
								<template #default="{row}">减免{{ row.couponDiscountAmount || 0 }}元</template>
							</vxe-column> -->
							<vxe-column title="费用周期" width="200">
								<template #default="{row}">{{ formatDate(row.beginTime) }} 至 {{ formatDate(row.endTime) }}</template>
							</vxe-column>
						</vxe-table>
					</template>
				</a-skeleton>
			</a-tab-pane>
			<a-tab-pane key="record" tab="审核状态">
				<a-steps progress-dot direction="vertical">
					<a-step status="process">
						<template #title>
							<a-tag color="processing">待审核</a-tag>
						</template>
						<template #description>
							<a-descriptions :column="1">
								<a-descriptions-item label="金额">{{ detail.totalMoney }}</a-descriptions-item>
								<a-descriptions-item label="摘要">{{ detail.billName }}</a-descriptions-item>
								<a-descriptions-item label="经办人">{{ detail.affirmEmpName }}</a-descriptions-item>
								<a-descriptions-item label="提交时间">{{ detail.createTime }}</a-descriptions-item>
								<a-descriptions-item label="支付时间">{{ detail.practicalTime }}</a-descriptions-item>
								<a-descriptions-item label="支付备注">{{ detail.comment }}</a-descriptions-item>
							</a-descriptions>
						</template>
					</a-step>
					<a-step v-if="detail.auditStatus > 1">
						<template #title>
							<a-tag :color="detail.auditStatus === 2 ? 'success' : 'error'">
								{{ detail.auditStatus === 2 ? '已通过' : '已驳回' }}
							</a-tag>
						</template>
						<template #description>
							<a-descriptions :column="1">
								<a-descriptions-item label="审核人">{{ detail.auditEmpName }}</a-descriptions-item>
								<a-descriptions-item label="审核时间">{{ detail.auditTime }}</a-descriptions-item>
								<a-descriptions-item label="审核意见">{{ detail.auditComment }}</a-descriptions-item>
							</a-descriptions>
						</template>
					</a-step>
				</a-steps>
			</a-tab-pane>
		</a-tabs>
		<template v-if="detail.auditStatus !== 3 && detail.isValid && ![1, '1'].includes(props.approvalStatus as number)" #footer>
			<a-button type="primary" v-action="['mk_finance_bill-flow_sh', 'mk_finance_bill-flow_qxsh']" @click="audit">
				{{ detail.auditStatus === 1 ? '审核' : '取消审核' }}
			</a-button>
		</template>
	</a-drawer>
	<bill-flow-audit-dialog v-model:visible="visibles.audit" :id="id" />
	<!-- 关联核销记录 -->
	<link-write-off-bill-record v-model:visible="visibles.isShowBillRecordDialog" :verifyId="verifyId" />
</template>

<script setup lang="ts">
	import {createVNode, reactive, ref, toRef, watchEffect} from 'vue'
	import {BillFLow} from '@/interface/bill'
	import {CloseOutlined, QuestionCircleOutlined} from '@ant-design/icons-vue'
	import {financeBillFlowAudit, getFinanceBillFlowDetail} from '@/api/details'
	import FileUpload from '@/components/common/file-upload.vue'
	import {formatDate} from 'yuxin-base/src/utils/date'
	import BillFlowAuditDialog from '@/components/finance/dialog/bill-flow-audit-dialog.vue'
	import {message, Modal} from 'ant-design-vue'
	import {VxeTablePropTypes} from 'vxe-table'
	import LinkWriteOffBillRecord from './link-write-off-bills-record.vue'
	import {isLockinEnv} from 'yuxin-base/src/utils'

	const props = defineProps<{
		id?: string
		visible: boolean
		approvalStatus?: string | number | null
	}>()

	const mapBankFlowType = {
		1: '企业批量核销',
		2: '线上支付',
		3: '手动提交'
	}
	const verifyId = ref<string | null>(null)

	const loadings = reactive({
		detail: false
	})

	const visibles = reactive({
		audit: false,
		isShowBillRecordDialog: false
	})

	const emits = defineEmits(['update:visible', 'close'])
	const options = reactive({
		width: 600,
		centered: true,
		placement: 'right',
		closable: false,
		destroyOnClose: true,
		getContainer: false,
		visible: toRef(props, 'visible'),
		style: {
			position: 'absolute'
		},
		bodyStyle: {
			padding: 0
		},
		maskStyle: {
			background: 'transparent'
		},
		footerStyle: {
			textAlign: 'right'
		},
		onClose() {
			emits('update:visible', false)
			setTimeout(() => emits('close'), 100)
		}
	})

	const detail = ref<BillFLow>({})
	const activeKey = ref('info')
	watchEffect(() => {
		if (props.visible && props.id) {
			activeKey.value = 'info'

			loadings.detail = true
			getFinanceBillFlowDetail(props.id)
				.then(({data}) => (detail.value = data))
				.finally(() => (loadings.detail = false))
		}
	})

	const audit = () => {
		if (detail.value.auditStatus === 1) {
			visibles.audit = true
		} else {
			Modal.confirm({
				title: '系统提示',
				centered: true,
				icon: createVNode(QuestionCircleOutlined),
				content: '确定要取消审核吗？',
				async onOk() {
					await financeBillFlowAudit({
						bizId: props.id,
						result: 3
					})
					message.success('取消审核成功')
				}
			})
		}
	}

	const openBillRecordDialog = () => {
		visibles.isShowBillRecordDialog = true
		verifyId.value = detail.value.verifyId
	}

	// 计算合计
	const sumNum = (list: any[], field: string) => {
		let count = 0
		list.forEach(item => {
			if (item.feeDirection === 1) {
				count += Number(item[field])
			} else {
				count -= Number(item[field])
			}
		})
		return count.toFixed(2)
	}
	const handleFormat = (data:any) => {
		const formatRes = data && data > -1 ? data / 100 : 0
		return isLockinEnv() ? formatRes : data
	}
	const footerMethod: VxeTablePropTypes.FooterMethod = ({columns, data}) => {
		return [
			columns.map((column, columnIndex) => {
				if (columnIndex === 0) {
					return '费用合计'
				}
				if (['money'].includes(column.field)) {
					return sumNum(data, column.field)
				}
				return null
			})
		]
	}
</script>

<style lang="less" scoped>
	:deep(.ant-drawer-right) {
		overflow: hidden;
	}
</style>
